package org.itboys.ace.web;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.tools.AdminCookieHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.seller.constant.CaliforniaSiteConstant;
import org.itboys.seller.dto.MatchRecordVO;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.*;
import org.itboys.seller.meta.Account;
import org.itboys.seller.meta.MatchInfo;
import org.itboys.seller.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hzliangchong1@corp.netease.com
 *         Date 2016/10/22.
 */
@RestController
@RequestMapping("/site")
public class SiteController extends BaseController {

    @Autowired
    private CaliforniaSiteUserService californiaSiteUserService;

    @Autowired
    private SellerUserService sellerUserService;

    @Autowired
    private AccountService accountService;


    @Autowired
    private RankingUserService rankingUserService;

    /**
     * 进入注册页面
     */
    @RequestMapping("/reg")
    public ModelAndView login(Model model,HttpServletRequest request){
        return new ModelAndView("site/reg");

    }

    /**
     * 进入基本信息页
     */
    @RequestMapping("/toBaseInfoVM")
    public ModelAndView toBaseInfoVM(Model model,HttpServletRequest request) {
        String userName = AdminCookieHolder.getAdminUserName();
        SellerUser sellerUser = sellerUserService.getAdminUser(userName);
        model.addAttribute("userInfo", sellerUser);
        return new ModelAndView("site/userBaseInfo");
    }

    /**
     * 更新信息
     */
    @RequestMapping("/editSeller")
    public void editSeller(@ModelAttribute SellerUser user,
                           HttpServletRequest request,HttpServletResponse response) {
        SellerUser proUser = sellerUserService.getAdminUser(user.getUserName());
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        SellerUser phoneUser = sellerUserService.getAdminUserByPhone(user.getPhone());
        if (phoneUser != null && !proUser.getUserName().equals(user.getUserName())) {
            AjaxUtils.renderText(response, CommonConstants.EXISTED);
            return;
        }
        proUser.setRealName(user.getRealName());
        proUser.setPhone(user.getPhone());
        proUser.setIdCard(user.getIdCard());
        proUser.setCompanyName(user.getCompanyName());
        sellerUserService.update(proUser);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }

    /**
     * 进入修改密码页
     */
    @RequestMapping("/toPassWordXg")
    public ModelAndView toPassWordXg(Model model,HttpServletRequest request) {
        return new ModelAndView("site/password-xg");
    }

    /**
     * 更新信息
     */
    @RequestMapping("/updateSellerPassword")
    public void updateSellerPassword(String oldPassword, String password,
                           HttpServletRequest request,HttpServletResponse response) {
        String userName = AdminCookieHolder.getAdminUserName();
        SellerUser proUser = sellerUserService.getAdminUser(userName);
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        if(!StringUtils.equals(proUser.getPassword(), Digests.md5(oldPassword))){
            AjaxUtils.renderText(response, "-1");//密码不正确
            return ;
        }
        proUser.setPassword(Digests.md5(password));
        sellerUserService.update(proUser);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }

    /**
     * 注册
     */
    @RequestMapping("/regMember")
    public void regMember(@ModelAttribute SiteUser user, int chargeAmount,
                          HttpServletRequest request,HttpServletResponse response) {
        String sellerUserName= AdminCookieHolder.getAdminUserName();
        SiteUser proUser = californiaSiteUserService.getAdminUserByPhone(user.getPhone());
        if (proUser != null) {
            AjaxUtils.renderText(response, CommonConstants.EXISTED);
            return;
        }
        if (user.getRecUserId() != 0) {
            proUser = californiaSiteUserService.getAdminUserByUserId(user.getRecUserId());
            if (proUser == null) {
                AjaxUtils.renderText(response, "推荐人不存在");
                return;
            }
        }
        user.setUserId(californiaSiteUserService.genUid());
        user.setSellerUserName(sellerUserName);
        californiaSiteUserService.insert(user);

        accountService.increaseToAudit(user.getUserId(), chargeAmount);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }

    /**
     * 更新信息
     */
    @RequestMapping("/editMember")
    public void editMember(@ModelAttribute SiteUser user,
                          HttpServletRequest request,HttpServletResponse response) {
        SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(user.getUserId());
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        SiteUser phoneUser = californiaSiteUserService.getAdminUserByPhone(user.getPhone());
        if (phoneUser != null && proUser.getUserId() != user.getUserId()) {
            AjaxUtils.renderText(response, CommonConstants.EXISTED);
            return;
        }
        if (user.getRecUserId() != 0) {
            SiteUser recUser = californiaSiteUserService.getAdminUserByUserId(user.getRecUserId());
            if (recUser == null) {
                AjaxUtils.renderText(response, "推荐人不存在");
                return;
            }
        }
        proUser.setMemberName(user.getMemberName());
        proUser.setRealName(user.getRealName());
        proUser.setPhone(user.getPhone());
        proUser.setRecUserId(user.getRecUserId());
        proUser.setIdCard(user.getIdCard());
        proUser.setCompanyName(user.getCompanyName());
        californiaSiteUserService.update(proUser);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }

    /**
     * 进入我的会员列表页面
     */
    @RequestMapping("/myfans")
    public ModelAndView myfans(Model model,HttpServletRequest request){
        return new ModelAndView("site/myFans");

    }

    @RequestMapping("/mySiteUserList")
    public void indexAllList(int pageNo, int pageSize,
                             HttpServletRequest request, HttpServletResponse response) {
        String sellerUserName= AdminCookieHolder.getAdminUserName();
        int offset = Math.max(0, (pageNo - 1) * pageSize);
        List<SiteUser> siteUserList = californiaSiteUserService.queryInfo(sellerUserName, offset, pageSize);
        List<Long> userIds = siteUserList.stream().map(SiteUser::getUserId).collect(Collectors.toList());
        List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
        List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
        Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Account> accounts = accountService.batchQueryAccount(userIds);
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = siteUserList.stream().map(p -> {
            SiteUserVO vo = new SiteUserVO();
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
            }
            SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
            if (recSiteUser != null) {
                vo.setRecMemberName(recSiteUser.getRealName());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(californiaSiteUserService.totalInfo(sellerUserName), voList, response);
    }

    /**
     * 进入会员充值页面
     */
    @RequestMapping("/toSiteCharge")
    public ModelAndView toSiteCharge(Model model,HttpServletRequest request){
        return new ModelAndView("site/charge");

    }

    /**
     * 充值
     */
    @RequestMapping("/charge")
    public void charge(long siteUserId, int chargeAmount,
                           HttpServletRequest request,HttpServletResponse response) {
        String sellerUserName= AdminCookieHolder.getAdminUserName();
        SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(siteUserId);
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        accountService.increaseToAudit(siteUserId, chargeAmount);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }


    @RequestMapping("/rankingList")
    public void rankingList(int pageNo, int pageSize,
                             HttpServletRequest request, HttpServletResponse response) {
        String sellerUserName= AdminCookieHolder.getAdminUserName();
        RankingUserDB rankingUserDB = rankingUserService.getLatestRankingUserBySellerUserName(0, sellerUserName);
        if (rankingUserDB == null) {
            return;
        }
        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getUserIds());
        List<Long> userIds = siteUserList.stream().map(SiteUser::getUserId).collect(Collectors.toList());
        List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
        List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
        Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Account> accounts = accountService.batchQueryAccount(userIds);
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = siteUserList.stream().map(p -> {
            SiteUserVO vo = new SiteUserVO();
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
            }
            SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
            if (recSiteUser != null) {
                vo.setRecMemberName(recSiteUser.getRealName());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }
}
